package com.kinroy.briefreport.annotation;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;

import java.lang.reflect.Method;

/**
 * 自定义注解的通知类
 *
 * @author kinroy
 */
@Component
@Aspect
@Slf4j
public class AnnotationAdvice {
    private long startTime;
    private long endTime;
    //在这里我们可以定义多个切面（对应我们自定义的多个注解）

    @Pointcut("@annotation(CalculateRuntime)")
    private void Calculate() {
    }


    @Pointcut("@annotation(PrintMethodName)")
    private void PrintName() {
    }

    @Around("Calculate()")
    public Object CalculateRuntime(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        log.info("========自定义注解@CalculateRuntime 生效===========");
        startTime = System.currentTimeMillis();
        //继续执行方法
        Object result = proceedingJoinPoint.proceed();
        //方法调用后，打印方法耗时
        endTime = System.currentTimeMillis();
        long resultTime = endTime - startTime;
        log.info("方法运行耗时：" + resultTime);
        log.info("========自定义注解@CalculateRuntime 结束===========");
        return result;
    }

    @Around("PrintName()")
    public Object PrintMethodName(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {

        //方法调用前
        MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature();
        //获取方法名称
        String methodName = methodSignature.getName();

        log.info("========自定义注解@PrintMethodName 生效===========");
        log.info("运行的方法的方法名为：" + methodName);
        log.info("========自定义注解@PrintMethodName 结束===========");
        Object proceed = proceedingJoinPoint.proceed();
        return proceed;
    }
}
